// Copyright (c) 2022 by Duguang.IO Inc. All Rights Reserved.
// Author: Ethan Liu
// Date: 2022-06-05 09:42:12

package command

import (
	"os"
	"runtime"

	"github.com/kelseyhightower/envconfig"
)

// Config 系统配置
type Config struct {
	Debug bool `envconfig:"JIANMU_DEBUG"`
	Trace bool `envconfig:"JIANMU_TRACE"`

	Logger struct {
		File       string `envconfig:"JIANMU_LOG_FILE"`
		MaxAge     int    `envconfig:"JIANMU_LOG_FILE_MAX_AGE"     default:"1"`
		MaxBackups int    `envconfig:"JIANMU_LOG_FILE_MAX_BACKUPS" default:"1"`
		MaxSize    int    `envconfig:"JIANMU_LOG_FILE_MAX_SIZE"    default:"100"`
	}

	Client struct {
		Address string `envconfig:"JIANMU_SRV_ADDRESS"   required:"true"`
		Secret  string `envconfig:"JIANMU_SRV_SECRET"    required:"true"`
	}

	Platform struct {
		OS   string `envconfig:"JIANMU_PLATFORM_OS"`
		Arch string `envconfig:"JIANMU_PLATFORM_ARCH"`
	}

	Worker struct {
		ID        string `envconfig:"JIANMU_WORKER_ID"    required:"true"`
		Name      string `envconfig:"JIANMU_WORKER_NAME"`
		Capacity  int    `envconfig:"JIANMU_WORKER_CAPACITY" default:"2"`
		Procs     int64  `envconfig:"JIANMU_WORKER_MAX_PROCS"`
		Tags      string `envconfig:"JIANMU_WORKER_TAGS"`
		Type      string `envconfig:"JIANMU_WORKER_TYPE" default:"KUBERNETES"`
		EnvFile   string `envconfig:"JIANMU_WORKER_ENVFILE"`
		Path      string `envconfig:"JIANMU_WORKER_PATH"`
		Root      string `envconfig:"JIANMU_WORKER_ROOT"`
		Config    string `envconfig:"JIANMU_KUBERNETES_CONFIG"`
		Namespace string `envconfig:"JIANMU_KUBERNETES_NAMESPACE" default:"default"`
	}

	Engine struct {
		ContainerStartTimeout int `envconfig:"JIANMU_ENGINE_CONTAINER_START_TIMEOUT" default:"480"`
	}

	KubernetesClient struct {
		QPS   float32 `envconfig:"JIANMU_KUBE_CLIENT_QPS"`
		Burst int     `envconfig:"JIANMU_KUBE_CLIENT_BURST"`
	}
}

// FromEnviron 从环境变量载入配置
func FromEnviron() (Config, error) {
	var config Config
	err := envconfig.Process("", &config)
	if err != nil {
		return config, err
	}
	if config.Worker.Name == "" {
		config.Worker.Name, _ = os.Hostname()
	}
	if config.Platform.OS == "" {
		config.Platform.OS = runtime.GOOS
	}
	if config.Platform.Arch == "" {
		config.Platform.Arch = runtime.GOARCH
	}

	return config, nil
}
